
package com.kingdee.eas.custom.aoyuan.aytime.bizbill.web;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;

import org.apache.commons.lang.StringUtils;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.action.ActionEvent;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.dao.query.QueryExecutorFactory;
import com.kingdee.bos.metadata.MetaDataPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.waf.action.AbstractWebAction;
import com.kingdee.bos.waf.ctx.WafContext;
import com.kingdee.bos.waf.winlet.BaseBean;
import com.kingdee.bos.workflow.monitor.IWfUtil;
import com.kingdee.bos.workflow.monitor.WfFacadeUtilFactory;
import com.kingdee.bos.workflow.service.ormrpc.EnactmentServiceFactory;
import com.kingdee.bos.workflow.service.ormrpc.IEnactmentService;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.org.PositionMemberCollection;
import com.kingdee.eas.basedata.org.PositionMemberFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.aoyuan.aytime.AYAttenBillStatusEnum;
import com.kingdee.eas.custom.aoyuan.aytime.ManagerWebUtil;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.IOTBill;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.jdbc.rowset.IRowSet;


@ManagedBean(name = "custom.aoyuan.aytime.bizbill.OTBillListUIBean", scope = ManagedBeanScope.SESSION)
public class OTBillListUIBean extends AbstractOTBillListUIBean {
	
	   public OTBillListUIBean()
	    {
			super();
	    	displayRows = 20;
	    }
	   
	   
	    
		protected void actionCloseBill_actionPerformed(ActionEvent event)
				throws AbortProcessingException {
			super.actionCloseBill_actionPerformed(event);
			closeSelectedModel();
			super.refresh();
		}



		@Bind
	    private String showHeight;
	    
	    @Bind
	    private int displayRows;
	    
	    @Bind
	    private boolean isManager=false;
	    
	    public void pageOnload()
	    {	
	    	setEntityViewInfoOnload();
	    	super.pageOnload();
	    	initShowHeight();  
	    }
	    
		public List<String> getBillSelIDList() {
			return super.getBillSelIDList();		
		}
	    
	    public void setEntityViewInfoOnload()
	    {
			PersonInfo personInfo = ContextUtil.getCurrentUserInfo(
					WafContext.getInstance().getContext()).getPerson();
			HROrgUnitInfo hrOrgInfo= ContextUtil.getCurrentHRUnit(WafContext.getInstance().getContext());

			if(hrOrgInfo!=null)
			{
				isManager = ManagerWebUtil.getManagerPermission(hrOrgInfo,"manager004");					
			}		
			EntityViewInfo entityViewInfo = new EntityViewInfo();
			FilterInfo filterInfo = new FilterInfo();	 
		    if(!isManager)
		    {
			  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));		    	
		    }else
			{
				filterInfo.getFilterItems().add(
						new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));
			}
			entityViewInfo.setFilter(filterInfo);
			
			//重新设置查询条件
			setEntityViewInfo(entityViewInfo);
	    }
	    
	    protected void mergeDefaultEntityViewInfo(EntityViewInfo entityViewInfo)
	    {
	    	PersonInfo personInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext()).getPerson();
			HROrgUnitInfo hrOrgInfo= ContextUtil.getCurrentHRUnit(WafContext.getInstance().getContext());
			if(hrOrgInfo!=null)
			{
				isManager = ManagerWebUtil.getManagerPermission(hrOrgInfo,"manager004");					
			}	
			FilterInfo filterInfo = new FilterInfo();	 
		    if(isManager)
		    { 
		    	if(StringUtils.isEmpty(entityViewInfo.toString()))
		    	{
					filterInfo.getFilterItems().add(
							new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));    
					entityViewInfo.setFilter(filterInfo);
		    	}else
		    	{
			    	try{
						filterInfo.getFilterItems().add(
								new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));   
		                this.entityViewInfo.getFilter().mergeFilter(filterInfo, "AND");
			    	}
	                catch(BOSException e)
	                {
	                    logger.warn("merge filter error:", e);
	                }    		
		    	}	
		    }else
		    {
		    	if(StringUtils.isEmpty(entityViewInfo.toString()))
		    	{
				  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));	
					entityViewInfo.setFilter(filterInfo);
		    	}else
		    	{
			    	try{
					  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));		
		                this.entityViewInfo.getFilter().mergeFilter(filterInfo, "AND");
			    	}
	                catch(BOSException e)
	                {
	                    logger.warn("merge filter error:", e);
	                }    		
		    	}		    	
		    }
	    }
	    
	    private PositionInfo getPosition(PersonInfo personInfo)
	    {
			PositionInfo positionInfo = null;
			EntityViewInfo entityViewInfo = new EntityViewInfo();
			FilterInfo filterInfo = new FilterInfo();
			filterInfo.getFilterItems().add(
					new FilterItemInfo("person.id", personInfo.getId(),
							CompareType.EQUALS));
			entityViewInfo.setFilter(filterInfo);
			IQueryExecutor iqec = QueryExecutorFactory.getRemoteInstance(new MetaDataPK(    
	                "com.kingdee.eas.custom.aoyuan.aytime.basedata.app",    
	                "PersonHRQuery"));
			try {
				iqec.setObjectView(entityViewInfo);  
				IRowSet irow = iqec.executeQuery();
				if(irow.size()>0)
				{
					if(irow.next())
					{
						 positionInfo=new PositionInfo();
						 HROrgUnitInfo hrOrg=new HROrgUnitInfo();
						 AdminOrgUnitInfo adminOrg=new AdminOrgUnitInfo();
						 String positionId=irow.getString("Position.id");
						 String positionName=irow.getString("Position.name");
						 positionInfo.setId(BOSUuid.read(positionId));
						 positionInfo.setName(positionName);
						 String hrOrgId=irow.getString("HROrgUnit.id");
						 String hrOrgName=irow.getString("HROrgUnit.name");
						 hrOrg.setId(BOSUuid.read(hrOrgId));
						 hrOrg.setName(hrOrgName);
						 hrOrg.setLongNumber(irow.getString("HROrgUnit.longNumber"));
						 String adminOrgId=irow.getString("AdminOrgUnit.id");
						 String adminOrgName=irow.getString("AdminOrgUnit.name");
						 adminOrg.setId(BOSUuid.read(adminOrgId));
						 adminOrg.setName(adminOrgName);
						 positionInfo.setAdminOrgUnit(adminOrg);
						 positionInfo.setHrOrgUnit(hrOrg);
					}
				}
	/*			PositionMemberCollection coll = PositionMemberFactory
						.getRemoteInstance().getPositionMemberCollection(
								entityViewInfo);
				for (int i = 0; i < coll.size(); i++) {
					if (coll.get(i).getPosition() != null) {
						positionInfo = coll.get(i).getPosition();
						if (positionInfo.getAdminOrgUnit() != null) {
							// 找到对应的岗位和行政组织
							break;
						}
					}
				}*/
				return positionInfo;
			} catch (BOSException e) {
				e.printStackTrace();
				return null;
			} catch (SQLException e) {
				e.printStackTrace();
				return null;
			}
	    }   
	    
		public void closeSelectedModel() {
			IOTBill iOTBill=(IOTBill)getBizInterface();
			List<String> IDs = getBillSelIDList();
			if(IDs.size()>0){
				for(int i = 0;i<IDs.size();i++){
					try {
						OTBillInfo info = getBillInfo(IDs.get(i));
						if(info!=null)
						{
							if(AYAttenBillStatusEnum.PASS.equals(info.getStatus())){
								iOTBill.closeBill(info);
							}else
							{
								if(info.getId()!=null)
								{
									IEnactmentService service = EnactmentServiceFactory.createRemoteEnactService();
									IWfUtil util = WfFacadeUtilFactory.createRemoteWfUtil();
									String procInstId = util.getProcInstId(info.getId().toString());
									service.abortProcessInst(procInstId);	
									info.setStatus(AYAttenBillStatusEnum.CLOSE);
									iOTBill.save(info);
								}					
							}
						}
					
					} catch (BOSException e) {
						e.printStackTrace();
						addMessage("操作成功！");
					} catch (EASBizException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			addMessage("操作成功！");
		}
		
		public void deleteSelectedModel() {
	        int rows[] = grid.getSelections();
	        if(!checkSelected(rows) || listModel == null || listModel.size() < 1)
	            return;
	        
	        int arr[] = rows;
	        int len = arr.length;
	        boolean isDel=true;
	        for(int i$ = 0; i$ < len; i$++)
	        {
	            int i = arr[i$];
	            Map rowData = (Map)listModel.get(i % grid.getRows());
	            if(!rowData.get("status").toString().equals(AYAttenBillStatusEnum.DRAFT.getAlias()))
	            {
	            	if(isDel)
	            	{
	            		addMessage("只有草拟能删除！");
	            		isDel=false;           		
	            	}
	            }
	        }
	        if(isDel)
	        {
	    		super.deleteSelectedModel();      	
	        }
		}
		
		private OTBillInfo getBillInfo(String ID) throws BOSException{
			EntityViewInfo evi = new EntityViewInfo();
			FilterInfo filter = new FilterInfo();
			if (ID != null) {
				filter.getFilterItems()
						.add(
								new FilterItemInfo("ID", ID,
										CompareType.EQUALS));
			}
			else{
				return null;
			}
			evi.setFilter(filter);
			SelectorItemCollection sic = new SelectorItemCollection();
			sic.add("*");
			sic.add("id");
			sic.add("entrys.*");
			evi.setSelector(sic);
			OTBillCollection cos = OTBillFactory.getRemoteInstance().getOTBillCollection(evi);
			if(cos.size()>0){
				return cos.get(0);
			}
			return null;
		}
		
	    protected String commQueryOptions()
	    {
	       StringBuffer opts = new StringBuffer();
	        opts.append("{");
	        opts.append("PARENT_PAGE_NAME").append(":'");
	        opts.append((new StringBuilder()).append(getClass().getName()).append("',").toString());
	        opts.append("QUERY_NAME").append(":'");
	        opts.append((new StringBuilder()).append(getQueryPK().getFullName()).append("'").toString());
	        String userQuery = getUserQueryView();
	        if(userQuery != null)
	        {
	            opts.append(",");
	            opts.append("USER_QUERY_VIEW").append(":'");
	            opts.append((new StringBuilder()).append(userQuery).append("'").toString());
	        }
	        opts.append("}");
	        return opts.toString();
	    }  
	    
	    protected void initShowHeight()
	    {
	        Object obj = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("clientHeight");
	        if(obj != null)
	            showHeight = obj.toString();
	        else
	            showHeight = "600";
	        Map params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
	        String objMethod = (String)params.get("fromMethod");
	        int tempHeight = Integer.parseInt(showHeight);
	        if("commonFunctionPortlet".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        if("commonFunctionPortlet".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        if("fastToolbar".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        {
	            showHeight = String.valueOf(tempHeight - 170);
	            displayRows = (tempHeight - 170 - 53) / 20;
	            if(tempHeight - 170 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        }
	    }   

}

